<?php
namespace service;
use think\Request;

class WechatService {

    private static $instance = null;
    /**
     * 微信配置
     */
    public static function options()
    {

        $config = [
            'token'          => '8WruhskzRM9YaKpc',
            'appid'          => 'wx4940ea9151a35cc7',
            'appsecret'      => '5e2caffe24e107a53174c4fe3c4f4da7',
            'encodingaeskey' => 'YFcWIJ9dmT0AMlIwCRo4Ko05JuQ5H8Vpo40fZjnQHYM',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id'         => "1537918001",
            'mch_key'        => '8e2caffe24e107a53174c4fe3c4f4da9',
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key'        => ROOT_PATH.'cert/apiclient_key.pem',
            'ssl_cer'        => ROOT_PATH.'cert/apiclient_cert.pem',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path'     => ROOT_PATH.'/runtime/cache/wechat/',
        ];
        return $config;
    }


    //微信菜单
    public static function menuService(){
        return  new \WeChat\Menu(self::options());
    }

 

    //消息接收
    public static function ReceiveService(){
        return new \WeChat\Receive(self::options());
    }

    /**
     * 标签管理
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public static function tagService(){
        return new \WeChat\Tags(self::options());
    }
    /**
     * js
     */
    public static function jsService(){
        return new \WeChat\Script(self::options());
    }

    /**
     * 媒体
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public static function mediaService(){
        return new \WeChat\Media(self::options());
    }

        /**
     * 客服消息
     */
    public static function customService(){
        return new \WeChat\Custom(self::options());
    }

    /**
     * 支付
     */
    public static function payService(){
        return new \WeChat\Pay(self::options());
    }


    public static function userService(){
        return new \WeChat\User(self::options());
    }

        /**
     * 模板消息
     */
    public static function templateService(){
        return new \WeChat\Template(self::options());
    }

    /**
     * 微信网页授权接口
     */
    public static function  wechatOauth(){
        return new \WeChat\Oauth(self::options());
    }

    /**
     * 授权获取用户信息
     */
    public static function getOriginal(){
        
        $result = self::wechatOauth()->getOauthAccessToken();
        if(Request::get('state') != 'base'){
           return self::wechatOauth()->getUserInfo($result['access_token'],$result['openid']);
        }else{
            return $result;
        }
    }

    /**
     * 获取用户信息
     * @param string $openid 用户openid
     * @return array
     */
    public function getUserInfo($openid){
        return self::userService()->getUserInfo($openid);
    }

    /**
     * 获取授权地址
     */
    public function getOauthRedirect($redirect_url, $state = '', $scope = 'snsapi_base'){
        return self::wechatOauth()->getOauthRedirect($redirect_url, $state = '', $scope = 'snsapi_base');
    }
        /**
     * 获得jsSdk支付参数
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @return array|string
     */
    public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
    {
        return self::payService()->createParamsForJsApi(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
    }

        /**
     * 获得下单ID
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @return mixed
     */
    public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
    {

        $order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
        $result = self::payService()->createOrder($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            // try{
            //     HookService::listen('wechat_payment_prepare',$order,$result->prepay_id,false,PaymentBehavior::class);
            // }catch (\Exception $e){}
            return $result->prepay_id;
        }else{
            if($result->return_code == 'FAIL'){
                exception('微信支付错误返回：'.$result->return_msg);
            }else if(isset($result->err_code)){
                exception('微信支付错误返回：'.$result->err_code_des);
            }else{
                exception('没有获取微信支付的预支付ID，请重新发起支付!');
            }
            exit;
        }

    }

        /**
     * 生成支付订单对象
     * @param $openid
     * @param $out_trade_no
     * @param $total_fee
     * @param $attach
     * @param $body
     * @param string $detail
     * @param string $trade_type
     * @param array $options
     * @return Order
     */
    protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
    {
        $total_fee = bcmul($total_fee,100,0);
        $order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
        if($order['detail'] == '') unset($order['detail']);
        return $order;
    }

    /**
     * 发送模板消息
     */
    public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = null)
    {
        return self::templateService()->send($data);
    }
    

        /**
     * 微信支付成功回调接口
     */
    public static function handleNotify()
    {
        return HookService::listen('wechat_pay_success',$notify,null,true,PaymentBehavior::class);
    }
}
